package cn.rayland.rayland3d.app;

import android.app.Application;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.rayland.library.utils.MachineManager;

/**
 * Created by gw on 4/18/16.
 */
public class App extends Application {

    private final static String configPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/machine.txt";
    public static MachineManager machineManager = null;

    @Override
    public void onCreate() {
        super.onCreate();

        //获取MachineManager对象
        machineManager = MachineManager.getInstance(this);
        //设置自定义机器配置
        File configFile = new File(configPath);
        if(!configFile.exists()){
            copyFromAssets(configPath.substring(configPath.lastIndexOf("/")+1), configPath);
        }
        machineManager.setCustomMachineConfig(configPath);
    }

    private void copyFromAssets(String assetsFilePath, String destiFilePath){
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = getAssets().open(assetsFilePath);
            File file = new File(destiFilePath);
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while((length = is.read(bytes))!=-1){
                fos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
